package com.biomatch.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.biomatch.domain.DancePosition;
import com.biomatch.dto.Pagination;
import com.biomatch.mapper.DancePositionMapper;
import com.biomatch.service.DancePositionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class DancePositionServiceImpl implements DancePositionService {
    @Autowired
    private DancePositionMapper dancePositionMapper;

    @Override
    public IPage<DancePosition> getAllPositionByPage(Pagination pagination) {
        Page<DancePosition> page = new Page<>(pagination.getCurrent(), pagination.getPageSize());
        return dancePositionMapper.selectPage(page, null);
    }

    @Override
    public List<DancePosition> getAll() {
        return dancePositionMapper.selectList(null);
    }

    @Override
    public DancePosition saveOrUpdate(DancePosition dancePosition) {

        if (dancePosition.getId() <= 0) {
            QueryWrapper<DancePosition> positionQueryWrapper = new QueryWrapper<>();
            positionQueryWrapper.eq("positionName", dancePosition.getPositionName());
            if (dancePositionMapper.selectCount(positionQueryWrapper) > 0) {
                return null;
            }
            else {
                String code = String.valueOf(new Date().getTime());
                dancePosition.setCoursePositionId("D"+code.substring(5, code.length()));
                dancePositionMapper.insert(dancePosition);
                return dancePosition;
            }
        } else {
            QueryWrapper<DancePosition> positionQueryWrapper = new QueryWrapper<>();
            positionQueryWrapper.eq("positionName", dancePosition.getPositionName()).ne("coursePositionId",dancePosition.getCoursePositionId());

            if (dancePositionMapper.selectCount(positionQueryWrapper) > 0) {
                return null;
            }
            else {
                dancePositionMapper.updateById(dancePosition);
                return dancePosition;
            }
        }
    }

    @Override
    public DancePosition delete(DancePosition dancePosition) {
        QueryWrapper<DancePosition> PositionQueryWrapper = new QueryWrapper<>();
        PositionQueryWrapper.eq("coursePositionId", dancePosition.getCoursePositionId());
        if (dancePositionMapper.selectCount(PositionQueryWrapper) > 0) {
            dancePositionMapper.deleteById(dancePosition.getId());
            return dancePosition ;
        } else
        {
            return null;
        }
    }
}
